/**
 * @author HuWen
 * @date 2025/8/11 10:28)
 */
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class LotteryDataProcessor {
    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://192.168.110.254:3306/test?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root123456";

    // 接口 URL
    private static final String API_URL =  "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=1";
    public static void main(String[] args) {
        try {
            // 1. 发送 HTTP 请求获取数据
            String responseJson = sendGetRequest(API_URL);
            // 2. 解析 JSON 数据
            JSONArray dataList = parseDataFromJson(responseJson);
            // 3. 将数据存入数据库
            saveDataToDatabase(dataList);
            System.out.println("数据获取并存储成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送 HTTP GET 请求
// 发送 HTTP GET 请求，添加 User-Agent 模拟浏览器
private static String sendGetRequest(String url) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    // 添加 User-Agent 模拟浏览器请求
    httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
    // 可选：添加 Referer 模拟来源（若接口有来源限制）
    httpGet.setHeader("Referer", "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=1"); // 替换为实际来源域名
    
    CloseableHttpResponse response = httpClient.execute(httpGet);
    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity, "UTF-8"); // 显式指定 UTF-8 编码
        }
    } finally {
        response.close();
    }
    return null;
}

    // 解析 JSON 数据，提取 list 部分
    private static JSONArray parseDataFromJson(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject dataObject = jsonObject.getJSONObject("value");
        if (dataObject != null) {
            return dataObject.getJSONArray("list");
        }
        return new JSONArray();
    }

    // 将数据存入数据库
    private static void saveDataToDatabase(JSONArray dataList) {
        String sql = "INSERT INTO lottery_draw " +
                "(draw_flow_fund, draw_flow_fund_rj, draw_pdf_url, estimate_draw_time, is_get_kjpdf, " +
                "is_get_xlpdf, lottery_draw_num, lottery_draw_result, lottery_draw_status, lottery_draw_status_no, " +
                "lottery_draw_time, lottery_equipment_count, lottery_game_name, lottery_game_num, lottery_game_pronum, " +
                "lottery_notice, lottery_notice_show_flag, lottery_paid_begin_time, lottery_paid_end_time, " +
                "lottery_promotion_flag, lottery_promotion_flag_rj, lottery_sale_begin_time, lottery_sale_endtime, " +
                "lottery_suspended_flag, lottery_unsort_drawresult, pdf_type, pool_balance_afterdraw, pool_balance_afterdraw_rj) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            conn.setAutoCommit(false); // 开启事务

            for (int i = 0; i < dataList.size(); i++) {
                JSONObject item = dataList.getJSONObject(i);

                pstmt.setString(1, item.getString("drawFlowFund"));
                pstmt.setString(2, item.getString("drawFlowFundRj"));
                pstmt.setString(3, item.getString("drawPdfUrl"));
                pstmt.setString(4, item.getString("estimateDrawTime"));
                pstmt.setInt(5, item.getInteger("isGetKjpdf"));
                pstmt.setInt(6, item.getInteger("isGetXlpdf"));
                pstmt.setString(7, item.getString("lotteryDrawNum"));
                pstmt.setString(8, item.getString("lotteryDrawResult"));
                pstmt.setInt(9, item.getInteger("lotteryDrawStatus"));
                pstmt.setString(10, item.getString("lotteryDrawStatusNo"));
                pstmt.setString(11, item.getString("lotteryDrawTime"));
                pstmt.setInt(12, item.getInteger("lotteryEquipmentCount"));
                pstmt.setString(13, item.getString("lotteryGameName"));
                pstmt.setString(14, item.getString("lotteryGameNum"));
                pstmt.setInt(15, item.getInteger("lotteryGamePronum"));
                pstmt.setInt(16, item.getInteger("lotteryNotice"));
                pstmt.setInt(17, item.getInteger("lotteryNoticeShowFlag"));
                pstmt.setString(18, item.getString("lotteryPaidBeginTime"));
                pstmt.setString(19, item.getString("lotteryPaidEndTime"));
                pstmt.setInt(20, item.getInteger("lotteryPromotionFlag"));
                pstmt.setInt(21, item.getInteger("lotteryPromotionFlagRj"));
                pstmt.setString(22, item.getString("lotterySaleBeginTime"));
                pstmt.setString(23, item.getString("lotterySaleEndtime"));
                pstmt.setInt(24, item.getInteger("lotterySuspendedFlag"));
                pstmt.setString(25, item.getString("lotteryUnsortDrawresult"));
                pstmt.setInt(26, item.getInteger("pdfType"));
                pstmt.setString(27, item.getString("poolBalanceAfterdraw"));
                pstmt.setString(28, item.getString("poolBalanceAfterdrawRj"));

                pstmt.addBatch(); // 添加到批处理
            }

            pstmt.executeBatch(); // 执行批处理
            conn.commit(); // 提交事务

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

